<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="350px"
    :before-close="handleClose"
  >
    <el-form
      :rules="rules"
      ref="formData"
      :model="formData"
      label-width="100px"
      label-postion="right"
      style="width: 280px"
      status-icon
    >
      <el-form-item label="新密码:" prop="newPassword">
        <el-input
          type="password"
          v-model="formData.newPassword"
          maxlength="40"
          placeholder="请输入新密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码:" prop="repPassword">
        <el-input
          type="password"
          v-model="formData.repPassword"
          maxlength="40"
          placeholder="请输入确认密码"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('formData')" size="mini"
          >确定</el-button
        >
        <el-button size="mini" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import * as api from "@/api/user.js";
export default {
  props: {
    userId: null,
    title: {
      //弹窗的标题
      type: String,
      default: "",
    },
    visible: {
      //弹出窗口
      type: Boolean,
      default: false,
    },
    remoteClose: Function,
  },
  data() {
    //自定义校验
    var validateRepPassword = (rule, value, callback) => {
      if (value !== this.formData.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      formData: {},
      rules: {
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            max: 40,
            message: "长度在6到40个字符之间",
            trigger: "blur",
          },
        ],
        repPassword: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          {
            validator: validateRepPassword,
            trigger: "blur",
          },
        ],
      },
    };
  },

  components: {},

  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formData.id = this.userId;
          api.updatePassword(this.formData).then((res) => {
            if (res.code == 20000) {
              this.$message({ message: "密码修改成功", type: "success" });
              this.handleClose();
            } else {
              this.$message({ message: res.message, type: "success" });
            }
          });
        } else {
          return false;
        }
      });
    },

    handleClose() {
      this.$refs["formData"].resetFields();
      //触发关闭页面
      this.remoteClose();
    },
  },
};
</script>

<style scoped>
</style>